import React from "react";
import { FlatList, Image, StyleSheet, Text } from "react-native";
import { Switch, View, TouchableOpacity } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import NavigationBar from "../common/NavigationBar";
import BasePage from "../BasePage";
import { IconImage } from "../../utils";
import { windowWidth } from "../../configs/platform";
import navigator from "../../utils/navigator";
import ListSeparator from "../common/ListSeparator";
import ViewUtils from "../../utils/ViewUtils";
import { inject, observer } from "mobx-react";
import ToastUtils from "../../utils/ToastUtils";
import { toJS } from "mobx";
import { NavigationEvents } from "react-navigation";
import WatermarkView from "../components/WatermarkView";
import { summary } from "../../net/common";
import { orderCount } from "../../net/order";

/**
 * 我的
 */
@inject("userStore", "appStore", "upgradeStore")
@observer
export default class MineIndex extends BasePage {

  constructor(props) {
    super(props);
    this.state = {
      menuList: [
        {
          label: "今日未配送",
          value: 0,
        },
        {
          label: "今日配送数",
          value: 0,
        },
        {
          label: "今日合计",
          value: 0,
        },
        {
          label: "(近7天)周合计",
          value: 0,
        },
        {
          label: "当月合计",
          value: 0,
        },
        {
          key: 'total',
          label: "点击查看总单量",
          value: 0,
        },
      ],
      isLoadedTotal: false,
    };
  }

  changeWorkStatus = () => {
    const { userInfo, setValue, session } = this.props.userStore;
    if (IsNullOrEmpty(toJS(userInfo)))
      return;
    axios.get(api.changeWorkState, {
      params: {
        state: userInfo.work == 0 ? 1 : 0,
        showLoading: true,
        token: global.token,
      },
    })
      .then(result => {
        let user = toJS(userInfo);
        let ses = toJS(session);
        user["work"] = userInfo.work == 0 ? 1 : 0;
        ses["customer"] = user;
        setValue("session", ses);
      }).catch((e) => {
      logger(e);
      e.msg && ToastUtils.showFailInfo(e.msg);
    });
  };

  componentDidMount() {
    super.componentDidMount();
    this.getSummary();
  }

  getSummary = (showLoading = false) => {
    const { menuList } = this.state
    summary({
      token: global.token,
      showLoading,
    }).then(res => {
        if (res.result) {
          let newMenuList = [];
          let todayNoCount = { label: "今日未配送", value: res.result.todayNoCount || 0 };
          newMenuList.push(todayNoCount);
          let todayCount = { label: "今日配送数", value: res.result.todayCount || 0 };
          newMenuList.push(todayCount);
          let todayTotalCount = { label: "今日合计", value: res.result.todayTotalCount || 0 };
          newMenuList.push(todayTotalCount);
          let weekCount = { label: "(近7天)周合计", value: res.result.weekCount || 0 };
          newMenuList.push(weekCount);
          let monthCount = { label: "当月合计", value: res.result.monthCount || 0 };
          newMenuList.push(monthCount);
          newMenuList.push(menuList.pop())
          this.setState({ menuList: newMenuList });
        }
      }).catch((e) => {
      logger(e);
      // e.msg && ToastUtils.showFailInfo(e.msg);
    });
  };


  render_item = ({ item, index }) => {
    const { isLoadedTotal, menuList } = this.state
    return (
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => {
          if (item.key === 'total') {
            orderCount().then(res => {
              menuList.forEach(m => {
                m.key === 'total' && (m.value = res.result?.totalCount || 0)
              })
              // logger('menuList', JSON.stringify)
              this.setState({menuList, isLoadedTotal: true})
            })
          }
        }}
        style={styles.menu}>
        <View style={{ ...styles.menu_container, backgroundColor: item.bgColor }}>
          <Text style={commonStyles.text_black_20_bold}>
            {
              item.key === 'total' && !isLoadedTotal ? '?' : item.value
            }
          </Text>
          <Text style={{ ...commonStyles.text_gray_13, marginTop: 5 }}>
            {item.label}
          </Text>
        </View>
      </TouchableOpacity>
    );
  };

  onDidFocus = () => {
    this.getSummary();
  };

  render() {
    const { menuList } = this.state;
    const { userInfo } = this.props.userStore;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationEvents
          onDidFocus={() => this.onDidFocus()}
        />
        <NavigationBar
          title={"我的"}
          backgroundColor={"transparent"}
          leftButton={ViewUtils.getLeftIconButton(() => this.getSummary(true), "reload1", "#555555")}
          rightButton={ViewUtils.getRightImgTextBtn("setting", "", () => navigator.navigate("AboutUs"), 18)}
        />
        <View flex>
          <WatermarkView />
          <View style={StyleSheet.absoluteFill} pointerEvents={"box-none"}>
            <View row centerV bg-white padding-15>
              <Image source={IconImage.ic_default_avatar} style={{ width: 50, height: 50 }} />
              <View flex row spread>
                <View marginL-10 spread>
                  <Text style={commonStyles.text_black}>{userInfo?.name}</Text>
                  <Text style={commonStyles.text_black}>{userInfo?.telNo}</Text>
                </View>
                {
                  IsNullOrEmpty(userInfo) ? null :
                    <View center spread>
                      <Switch value={userInfo.work == 1} offColor={"#cccccc"}
                              onValueChange={(value) => this.changeWorkStatus()} />
                      <Text
                        style={{ ...commonStyles.text_black, marginTop: 5 }}>{userInfo.work == 1 ? "开始接单" : "停止接单"}</Text>
                    </View>
                }
              </View>
            </View>
            <View flex>
              <FlatList
                data={menuList}
                onRefresh={this._renderRefresh}
                showsVerticalScrollIndicator={false}
                extraData={this.state}
                style={{ marginTop: 10 }}
                keyExtractor={(item, index) => "pro_" + index}
                renderItem={this.render_item}
                numColumns={3}
                ItemSeparatorComponent={() => <ListSeparator height={1} backgroundColor={"transparent"} />}
              />
            </View>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  bg_mine: {
    width: "100%",
    height: windowWidth * 365 / 750,
  },
  edit: {
    width: 85,
    height: 28,
    borderBottomLeftRadius: 14,
    borderTopLeftRadius: 14,
    backgroundColor: "#3FC377",
    ...commonStyles.center,
    alignSelf: "flex-end",
    marginTop: 5,
  },
  card: {
    width: windowWidth - 20,
    alignSelf: "center",
    borderRadius: 5,
    backgroundColor: "white",
    alignItems: "center",
    paddingBottom: 20,
    marginTop: 30,
    minHeight: 400,
  },
  menu: {
    ...commonStyles.center,
    width: "33.3%",
    backgroundColor: "white",
    marginRight: 1,
  },
  menu_container: {
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 5,
    width: 98,
    height: 70,
  },
  avatar: {
    width: 58,
    height: 58,
    borderRadius: 29,
  },
  avatar_container: {
    flexDirection: "row",
    alignItems: "center",
    paddingLeft: 25,
  },
});
